react 您所在的位置:网站首页 react native ant design react

react

#react| 来源: 网络整理| 查看: 265

Vector Icons for React Native

Travis npm npm

Perfect for buttons, logos and nav/tab bars. Easy to extend, style and integrate into your project.

If you want to use .svg files natively – try react-native-vector-image.

Table of Contents Bundled Icon Sets Installation iOS Android OSX Windows Web Upgrading Icon Component Icon.Button Component Usage as PNG image/source object TabBar Multi-style fonts Custom Fonts Animation Examples Generating your own icon set from a CSS file Changelog Troubleshooting License Sponsoring

If you find the library useful, please consider sponsoring. Things I have planned is to split up the repo into a monorepo, that would enable individual versioning of icon sets, better performance, smaller bundle and easier for the community to publish their own.

Bundled Icon Sets

Browse all.

AntDesign by AntFinance (298 icons) Entypo by Daniel Bruce (v1.0.1 411 icons) EvilIcons by Alexander Madyankin & Roman Shamin (v1.10.1, 70 icons) Feather by Cole Bemis & Contributors (v4.28.0, 286 icons) FontAwesome by Dave Gandy (v4.7.0, 675 icons) FontAwesome 5 by Fonticons, Inc. (v5.15.3, 1598 (free) 7848 (pro) icons) FontAwesome 6 by Fonticons, Inc. (v6.1.2, 2016 (free) 16150 (pro) icons) Fontisto by Kenan Gündoğan (v3.0.4, 615 icons) Foundation by ZURB, Inc. (v3.0, 283 icons) Ionicons by Ionic (v7.1.0, 1338 icons) MaterialIcons by Google, Inc. (v4.0.0, 2189 icons) MaterialCommunityIcons by MaterialDesignIcons.com (v6.5.95, 6596 icons) Octicons by Github, Inc. (v16.3.1, 250 icons) Zocial by Sam Collins (v1.4.0, 100 icons) SimpleLineIcons by Sabbir & Contributors (v2.5.5, 189 icons) Installation Run: $ npm install --save react-native-vector-icons For each platform (iOS/Android/Windows) you plan to use, follow one of the options for the corresponding platform. Check out these guides if you intend to use FontAwesome 5 or 6 to get you started: FontAwesome 5 FontAwesome 6 iOS

If you want to use any of the bundled icons, you need to add the icon fonts to your Xcode project. Just follow these steps:

Browse to node_modules/react-native-vector-icons and drag the folder Fonts (or just the ones you want) to your project in Xcode. Make sure your app is checked under "Add to targets" and that "Create groups" is checked if you add the whole folder. Not familiar with Xcode? Try this article Edit Info.plist and add a property called Fonts provided by application (or UIAppFonts if Xcode won't autocomplete/not using Xcode) and type in the files you just added. It will look something like this:

XCode screenshot

List of all available fonts to copy & paste in Info.plist UIAppFonts AntDesign.ttf Entypo.ttf EvilIcons.ttf Feather.ttf FontAwesome.ttf FontAwesome5_Brands.ttf FontAwesome5_Regular.ttf FontAwesome5_Solid.ttf FontAwesome6_Brands.ttf FontAwesome6_Regular.ttf FontAwesome6_Solid.ttf Foundation.ttf Ionicons.ttf MaterialIcons.ttf MaterialCommunityIcons.ttf SimpleLineIcons.ttf Octicons.ttf Zocial.ttf Fontisto.ttf

In your XCode Settings, in the Build Phases tab, under Copy Bundle Resources add the fonts you have copied in the Fonts directory.

When using auto linking, it will automatically add all fonts to the Build Phases, Copy Pods Resources. Which will end up in your bundle. To avoid that, create a react-native.config.js file at the root of your react-native project with:

module.exports = { dependencies: { 'react-native-vector-icons': { platforms: { ios: null, }, }, }, };

Note: you need to recompile your project after adding new fonts.

Android Option: With Gradle (recommended)

This method has the advantage of fonts being copied from this module at build time so that the fonts and JS are always in sync, making upgrades painless.

Edit android/app/build.gradle ( NOT android/build.gradle ) and add the following:

apply from: file("../../node_modules/react-native-vector-icons/fonts.gradle")

To customize the files being copied, add the following instead:

project.ext.vectoricons = [ iconFontNames: [ 'MaterialIcons.ttf', 'EvilIcons.ttf' ] // Name of the font files you want to copy ] apply from: file("../../node_modules/react-native-vector-icons/fonts.gradle"); Monorepo configuration If you are working in a monorepo, you'll need to point to the correct location of the `fonts.gradle` script and of the Font files, **relative to the android/app/build.gradle file**. For example if your repo uses this common structure: your-monorepo/ ├─ node_modules/ │ ├─ react-native-vector-icons ├─ apps/ │ ├─ YourApp/ │ │ ├─ android/ │ │ │ ├─ app/ │ │ │ │ ├─ build.gradle

you will need to update the paths to:

project.ext.vectoricons = [ + iconFontsDir: "../../../../node_modules/react-native-vector-icons/Fonts", iconFontNames: ["WhateverFonts", "..."] ] - apply from: "../../node_modules/react-native-vector-icons/fonts.gradle" + apply from: "../../../../node_modules/react-native-vector-icons/fonts.gradle

⚠️ There have been reported issues when using RNVI < 9.0.0 in a monorepo, so make sure you are on 9+.

Option: Manually Copy the contents in the Fonts folder to android/app/src/main/assets/fonts (note lowercase fonts folder). Integrating library for getImageSource support

These steps are optional and only needed if you want to use the Icon.getImageSource function.

Edit android/settings.gradle to look like this (without the +):

rootProject.name = 'MyApp' include ':app' + include ':react-native-vector-icons' + project(':react-native-vector-icons').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-vector-icons/android')

Edit android/app/build.gradle (note: app folder) to look like this:

apply plugin: 'com.android.application' android { ... } dependencies { implementation fileTree(dir: "libs", include: ["*.jar"]) //noinspection GradleDynamicVersion implementation "com.facebook.react:react-native:+" // From node_modules + implementation project(':react-native-vector-icons') }

Edit your MainApplication.java (deep in android/app/src/main/java/...) to look like this (note two places to edit):

Note: this is optional step, it's necessary only and only if your react-native app doesn't support auto-linking otherwise you can ignore this.

package com.myapp; + import com.oblador.vectoricons.VectorIconsPackage; .... @Override protected List getPackages() { return Arrays.asList( new MainReactPackage() + , new VectorIconsPackage() ); } } macOS via react-native-macos Browse to node_modules/react-native-vector-icons and drag the folder Fonts to your project in Xcode. Make sure your app is checked under "Add to targets" and that "Create folder references" is checked. Edit Info.plist and add a property called Application fonts resource path (or ATSApplicationFontsPath if Xcode won't autocomplete/not using Xcode) and type Fonts as the value.

Note: you need to recompile your project after adding new fonts, also ensure that the Fonts folder also appear under Copy Bundle Resources in Build Phases.

Windows via react-native-windows In the top level projects (/windows/project-name/Assets), copy and paste the font files. Open your solution in Visual Studio, right click the Assets folder in your solution, click Add > Existing Item. Select the fonts that were into /windows/project-name/assets and click Add.

Note: you need to recompile your project after adding new fonts.

Web (with webpack)

In your webpack configuration file, add a section to handle ttf files using url-loader (or file-loader)

{ test: /\.ttf$/, loader: "url-loader", // or directly file-loader include: path.resolve(__dirname, "node_modules/react-native-vector-icons"), },

Then consume those files in your JavaScript entry point to get the bundled url and inject a style tag in your page:

// Use prebuilt version of RNVI in dist folder import Icon from 'react-native-vector-icons/dist/FontAwesome'; // Generate required css import iconFont from 'react-native-vector-icons/Fonts/FontAwesome.ttf'; const iconFontStyles = `@font-face { src: url(${iconFont}); font-family: FontAwesome; }`; // Create stylesheet const style = document.createElement('style'); style.type = 'text/css'; if (style.styleSheet) { style.styleSheet.cssText = iconFontStyles; } else { style.appendChild(document.createTextNode(iconFontStyles)); } // Inject stylesheet document.head.appendChild(style); Upgrading

Upgrading this package often requires the font files linked to your projects to be updated as well. If the automatic linking works for you, running this again should update the fonts. Otherwise you need to follow the steps outlined in the installation section.

Icon Component

You can either use one of the bundled icons above or roll your own custom font.

import Icon from 'react-native-vector-icons/FontAwesome'; const myIcon = ; Properties

Any Text property and the following:

Prop Description Default size Size of the icon, can also be passed as fontSize in the style object. 12 name What icon to show, see Icon Explorer app or one of the links above. None color Color of the icon. Inherited Static Methods Prop Description getFontFamily Returns the font family that is currently used to retrieve icons as text. Usage: const fontFamily = Icon.getFontFamily() getImageSource Returns a promise that resolving to the source of a bitmap version of the icon for use with Image component et al. Usage: const source = await Icon.getImageSource(name, size, color) getImageSourceSync Same as getImageSource but synchronous. Usage: const source = Icon.getImageSourceSync(name, size, color) getRawGlyphMap Returns the raw glyph map of the icon set. Usage: const glyphMap = Icon.getRawGlyphMap() hasIcon Checks if the name is valid in current icon set. Usage: const isNameValid = Icon.hasIcon(name) Styling

Since Icon builds on top of the Text component, most style properties will work as expected, you might find it useful to play around with these:

backgroundColor borderWidth borderColor borderRadius padding margin color fontSize

NOTE: On android Text doesn't currently support border* styles, to circumvent this simply wrap your Icon with a View.

By combining some of these you can create for example :

type star

Icon.Button Component

A convenience component for creating buttons with an icon on the left side.

import Icon from 'react-native-vector-icons/FontAwesome'; const myButton = ( Login with Facebook ); const customTextButton = ( Login with Facebook );

buttons

Properties

Any Text, TouchableHighlight or TouchableWithoutFeedback property in addition to these:

Prop Description Default color Text and icon color, use iconStyle or nest a Text component if you need different colors. white size Icon size. 20 iconStyle Styles applied to the icon only, good for setting margins or a different color. Note: use iconStyle for margins or expect unstable behaviour. {marginRight: 10} backgroundColor Background color of the button. #007AFF borderRadius Border radius of the button, set to 0 to disable. 5 onPress A function called when the button is pressed. None Usage as PNG image/source object

Convenient way to plug this in into other components that rely on bitmap images rather than scalable vector icons. Takes the arguments name, size and color as described above.

Icon.getImageSource('user', 20, 'red').then(source => this.setState({ userIcon: source }) );

Alternatively you may use the synchronous method Icon.getImageSourceSync to avoid rendering glitches. Keep in mind that this method is blocking and might incur performance penalties. Subsequent calls will use cache however.

Multi-style fonts

Some fonts today use multiple styles, FontAwesome 5 for example, which is supported by this library. The usage is pretty much the same as the standard Icon component:

import Icon from 'react-native-vector-icons/FontAwesome5'; const myIcon1 = ; // Defaults to regular const myIcon2 = ; const myIcon3 = ; // Only in FA5 Pro Static methods

All static methods from Icon is supported by multi-styled fonts.

Prop Description getFontFamily Returns the font family that is currently used to retrieve icons as text. Usage: const fontFamily = Icon.getFontFamily(style) getImageSource Returns a promise that resolving to the source of a bitmap version of the icon for use with Image component et al. Usage: const source = await Icon.getImageSource(name, size, color) getImageSourceSync Same as getImageSource but synchronous. Usage: const source = Icon.getImageSourceSync(name, size, color) getRawGlyphMap Returns the raw glyph map of the icon set. Usage: const glyphMap = Icon.getRawGlyphMap(style) hasIcon Checks if the name is valid in current icon set. Usage: const isNameValid = Icon.hasIcon(name, style) getStyledIconSet Use this to get a Icon component for a single style. Usage. const StyledIcon = Icon.getStyledIconSet(style)

If no style argument is passed (or if it's invalid) the methods will default to a pre-defineds fallback.

Components

Icon.Button is supported, usage is just like Icon:

import Icon from 'react-native-vector-icons/FontAwesome5'; const myButton = ( Login with Facebook ); Custom Fonts createIconSet(glyphMap, fontFamily[, fontFile])

Returns your own custom font based on the glyphMap where the key is the icon name and the value is either a UTF-8 character or it's character code. fontFamily is the name of the font NOT the filename. Open the font in Font Book.app or similar to learn the name. Optionally pass the third fontFile argument for android support, it should be the custom font file name.

import { createIconSet } from 'react-native-vector-icons'; const glyphMap = { 'icon-name': 1234, test: '∆' }; const Icon = createIconSet(glyphMap, 'FontName', 'font-name.ttf'); createIconSetFromFontello(config[, fontFamily[, fontFile]])

Convenience method to create a custom font based on a fontello config file. Don't forget to import the font as described above and drop the config.json somewhere convenient in your project.

import { createIconSetFromFontello } from 'react-native-vector-icons'; import fontelloConfig from './config.json'; const Icon = createIconSetFromFontello(fontelloConfig); createIconSetFromIcoMoon(config[, fontFamily[, fontFile]]) import { createIconSetFromIcoMoon } from 'react-native-vector-icons'; import icoMoonConfig from './selection.json'; const Icon = createIconSetFromIcoMoon( icoMoonConfig, 'LineAwesome', 'line-awesome.ttf' );

Make sure you're using the Download option in IcoMoon, and use the .json file that's included in the .zip you've downloaded. You'll also need to import the .ttf font file into your project, following the instructions above.

createMultiStyleIconSet(styles [, options]) import { createMultiStyleIconSet } from 'react-native-vector-icons'; /* * This is just example code, you are free to * design your glyphmap and styles to your liking */ import glyphmap from './glyphmap.json'; /* * glyphmap = { * "style1": [ * "hello", * "world" * ], * "style2": [ * "foo", * "bar" * ] * } */ const glyphKeys = Object.keys(glyphmap); /* ["style1", "style2"] */ const options = { defaultStyle: 'style1', glyphValidator: (name, style) => glyphKeys.indexOf(name) !== -1, fallbackFamily: (name) => { for (let i = 0; i true iOS

You have to manually make a reference of your .ttf on your xcodeproj Resources folder and in Info.plist.

Animation

React Native comes with an amazing animation library called Animated. To use it with an icon, simply create an animated component with this line: const AnimatedIcon = Animated.createAnimatedComponent(Icon). You can also use the higher level animation library react-native-animatable.

Examples IconExplorer

Try the IconExplorer project in Examples/IconExplorer folder, there you can also search for any icon.

Screenshot of IconExplorer

Basic Example import Icon from 'react-native-vector-icons/Ionicons'; function ExampleView(props) { return ; } TabBar

Since TabBarIOS was removed from core in favor of @react-navigation/bottom-tabs, it is also removed as a convenience component from this library. Simply use the Icon instead, but don't forget to import and link to this project as described above first.

Below is an example taken from react-navigation:

import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'; import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons'; const Tab = createBottomTabNavigator(); function MyTabs() { return ( ( ), }} /> ( ), tabBarBadge: 3, }} /> ( ), }} /> ); } ToolbarAndroid

Since ToolbarAndroid was removed from core, it is also removed as a convenience component from this library. Simply use getImageSourceSync instead, but don't forget to import and link to this project as described above first.

import ToolbarAndroid from '@react-native-community/toolbar-android'; import Icon from 'react-native-vector-icons/Ionicons'; const navIcon = Icon.getImageSourceSync('md-arrow-back', 24, 'white'); const overflowIcon = Icon.getImageSourceSync('md-more', 24, 'white'); const settingsIcon = Icon.getImageSourceSync('md-settings', 30, 'white'); const twitterIcon = Icon.getImageSourceSync('logo-twitter', 25, '#4099FF'); function ToolbarView(props) { return ( ); } Inline Icons import { Text } from 'react-native'; import Icon from 'react-native-vector-icons/Ionicons'; function ExampleView(props) { return ( Lorem Ipsum ); } Generating your own icon set from a CSS file

If you already have an icon font with associated CSS file then you can easily generate a icon set with the generate-icon script.

Example usage: ./node_modules/.bin/generate-icon path/to/styles.css --componentName=MyIcon --fontFamily=myicon > Components/MyIcon.js Options

Any flags not listed below, like --componentName and --fontFamily, will be passed on to the template.

-p, --prefix

CSS selector prefix [default: ".icon-"]

-t, --template

Template in JS template string format [default: "./template/iconSet.tpl"]

For default template please provide --componentName and --fontFamily.

-o, --output

Save output to file, defaults to STDOUT

Changelog Troubleshooting The icons show up as a crossed out box on Android Make sure you've copied the font to android/app/src/main/assets/fonts. Delete the build folder with rm -rf android/app/build. Recompile the project. Red screen with "Unrecognized font family" error on iOS Make sure you've added manually the reference of your .ttf on your xcodeproj Resources folder. Check that the font you are trying to use appears in Info.plist, if you've added the whole folder and it's blue in color, then you need to add it to the path. Check that the font is copied in the Copy Bundle Resources in Build Phases. Delete the build folder with rm -rf ios/build Recompile the project. Android build fails on Windows for no good reason

Both npm and android file hierarchies tend to get very deep and even worse when you combine them. Since Windows file system has a max length, long file name addresses will result in numerous errors including Execution failed for task ':react-native-vector-icons:processReleaseResources'. So try to keep the path to your project folder as short as possible.

Wrong icons are shown after upgrading this package

You probably didn't update the font files linked to your native project after upgrading. However, this only applies to Android targets since iOS bundles the fonts when building the app (try to clean your build from Xcode if the problem exists). On android you can relink the project or you manually update the fonts. To have them automatically synced use the gradle approach.

Some icons are missing after upgrading this package

Sometimes vendors decides to remove some icons from newer releases, this has nothing to do with this package. If you depend on an older version of a font you can add it as a custom font.

License

This project is licenced under the MIT License.

Any bundled fonts are copyright to their respective authors and mostly under MIT or SIL OFL.



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有